<?php

/**
 * Regisztrációs oldal generálása
 *
 * @author poli
 */
class RegistrationPageGenerator extends BaseContentGenerator {

	private $_initialized = false;

	public function RegistrationPageGenerator($context, $generatorId, $iniParams = null, $skipIniParamsUpdateFromRequest = false) {
		parent::BaseContentGenerator("RegistrationPage", $context, $generatorId, $iniParams, $skipIniParamsUpdateFromRequest);
	}

	/**
	 * Mi most használjuk az iniParams tömbünket nagyon is! Úhygogy nosza, dolgozzuk fel
	 * belőle a dolgokat!
	 *
	 * @see site/contentGenerators/BaseContentGenerator#processSavedIniParams()
	 */
	public function processSavedIniParams($savedIniParams) {
		$this->_iniParams = $savedIniParams;
	}

	protected function _init() {			
		if($this->_initialized) return;
		$this->_initialized = true;			
	}

	/**
	* Hasonló a page enterPage metódusához. Akkor kerül meghívásra, amikor a
	* content generátor képernyőre kerül először. Azaz: az előző kérésre adott
	* válaszban még nem ő generálta a content-et
	*
	* Itt meg lehet valósítani mindenféle inicializálást, aminek csak egyszer kell
	* lefutni amíg a generátor aktív.
	*
	*/
	public function enterContentGenerator() {
		parent::enterContentGenerator();
	
		$gender = array(
			't' => TextHandler::getText('gender_male'),
			'f' => TextHandler::getText('gender_female')
		);
	
		// definiáljuk a form elemeit
		FormUtil::addForm("siteuser");
		FormUtil::addFormElement("siteuser", new FormElementInfo("name", "text"));
		FormUtil::addFormElement("siteuser", new FormElementInfo("email", "text"));
		FormUtil::addFormElement("siteuser", new FormElementInfo("birthyear", "text"));
		FormUtil::addFormElement("siteuser", new FormElementInfo("gender", "select", null, array('arrayType' => 'simpleArray', 'array' => $gender, "translateLabels" => false)));
		FormUtil::addFormElement("siteuser", new FormElementInfo("password", "text"));
		FormUtil::addFormElement("siteuser", new FormElementInfo("passwordconfirm", "text"));
		FormUtil::addFormElement("siteuser", new FormElementInfo("acceptTerms", "checkbox"));
		FormUtil::resetFormValues("siteuser");
	}
	
	/**
	 * Hasonló a page leavePage metódusához. Akkor kerül meghívásra amikor a user
	 * elhagyja a content generátort. Azaz eddig ő generálta a válaszokba a tartalmat, de
	 * most más valaki generálja.
	 *
	 * Itt meg lehet valósítani mindenféle cleanup dolgokat a kilépés kapcsán.
	 */
	public function leaveContentGenerator() {
		parent::leaveContentGenerator();
	
		FormUtil::removeAllForms();
	}

	public function serveRequest() {
		parent::serveRequest();

		$this->_init();

		SiteBase::setPageTitle(TextHandler::getText('reg_title'));
			
		$action = FunctionLibrary::getGetOrPostValueSmart('action', null);
		if(!is_null($action)) {
			$action = 'action_'.$action;
			$this->$action();
		}

		$tpl = BaseContentGenerator::loadTemplateFile("person_registration.tpl.html");
			
		TextHandler::insertTextsIntoTemplate($tpl, null, 'gen_');
		TextHandler::insertTextsIntoTemplate($tpl, null, 'reg_');
		FormUtil::insertFormValuesToTemplate('siteuser', $tpl);
		$tpl->setVariable('app_root_url', APP_ROOT_URL);
		$tpl->setVariable('link_update', LinkProvider::getLink('registrationPage'));

		$tpl->setVariable('link_form', UrlUtil::getRequestUrl());

		return $tpl->get();
	}

	protected function action_register() {
		$redirectUrl = LinkProvider::getLink('registrationPage');
		
		// form értékeket mentjük!
		FormUtil::fillFormValuesFromRequest('siteuser');
		// értékek kiolvasása
		$formValues = FormUtil::getFormValues('siteuser');
		
		try {
			$this->checkData('add', $formValues);

			$regId = FunctionLibrary::generate_password(10);
			$formValues['reg_id'] = $regId;
			$id = SiteDBHelper::addSiteUser($formValues);

			// siker!
			FormUtil::resetFormValues('siteuser');

			// email küldés
			$site = SiteHandler::getCurrentSite();
			$variables = array('siteName' => $site->name);
			$recipients = array();
			$recipient = new AlertRecipient();
			$recipient->sendHere = $formValues['email'];
			$recipient->langcodes = array(TextHandler::getCurrentLangcode());
			$regLink = ContentUrlManager::getContentGeneratorUrl(SiteHandler::getCurrentSiteId(), 'RegistrationPage', TextHandler::getCurrentLangcode(), "full");
			$regLink = UrlUtil::addRequestParametersToUrl($regLink, array('regId' => $regId, 'action' => 'confirm'));
			$recipient->variables = array('name' => $formValues['name'], 'regLink' => $regLink);
			$recipients[] = $recipient;
			AlertHandler::sendEmailAlert('registration.tpl.email', $recipients, $variables);

			handleSuccess(TextHandler::getText('reg_success'), $redirectUrl);
			exit();
		} catch (ParameterException $e) {
			$errorStrings = $e->getErrors();
		} catch (Exception $e) {
			$logErrorString = "adding new siteuser failed";
			Log::error('following errors occured during operation: '.$logErrorString);
			$errorStrings = array($e->getMessage());
		}

		handleError(TextHandler::getParsedText('reg_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $redirectUrl);
		exit();
	}

	protected function action_confirm() {
		$redirectUrl = LinkProvider::getLink('registrationPage');

		// reg id
		$regId = FunctionLibrary::getGetValueSmart('regId', null);
		
		try {
			$record = SiteDBHelper::confirmSiteUser($regId);
			if ($record === false) {
				$errorStrings = TextHandler::getText('reg_err_wrongcode');
				handleError(TextHandler::getParsedText('reg_confirm_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $redirectUrl);
			} else {
				handleSuccess(TextHandler::getText('reg_confirm_success'), $redirectUrl);
			}
		} catch (Exception $e) {
			$logErrorString = "adding new siteuser failed";
			Log::error('following errors occured during operation: '.$logErrorString);
			$errorStrings = array($e->getMessage());
			handleError(TextHandler::getParsedText('reg_confirm_failed', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $redirectUrl);
		}
		exit();
	}

	protected function checkData($type, $formValues) {
		$errors = new ParameterException();

		if (empty($formValues['email'])) {
			$errors->addError(TextHandler::getText('reg_err_emailempty'));
		} else if (! FunctionLibrary::checkEmailSyntax($formValues['email'])) {
			$errors->addError(TextHandler::getText('reg_err_emailsyntax'));
		} else {
			$filter = new DBQueryFilter();
			$filter->addComponent('email', DBQueryFilter::OP_EQUALS, $formValues['email']);
			$record = GeneralDBHelper::getTableRowFiltered('siteuser', $filter);
			if (!is_null($record)) {
				$errors->addError(TextHandler::getText('reg_err_emailoccupied'));
			}
		}

		if (empty($formValues['name'])) {
			$errors->addError(TextHandler::getText('reg_err_nameempty'));
		}

		if (empty($formValues['birthyear'])) {
			$errors->addError(TextHandler::getText('reg_err_birthyearempty'));
		} else if (! is_numeric($formValues['birthyear']) || $formValues['birthyear'] < 1900 || $formValues['birthyear'] > date('Y')) {
			$errors->addError(TextHandler::getText('reg_err_birthyearsyntax'));
		}

		if (empty($formValues['password'])) {
			$errors->addError(TextHandler::getText('reg_err_passwordempty'));
		} else if ($formValues['password'] != $formValues['passwordconfirm']) {
			$errors->addError(TextHandler::getText('reg_err_passwordconfirm'));
		}

		if (empty($formValues['acceptTerms'])) {
			$errors->addError(TextHandler::getText('reg_err_acceptTerms'));
		}

		if ($errors->hasError()) throw $errors;
	}

}
?>